import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpRouterService } from '../../service/http-router.service';
import { HttpService } from '../../service/http.service';
import { StorageService } from '../../service/storage.service';
import * as _ from 'underscore';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {

  public mobile = '';
  public password = '';
  public preference = '';

  constructor(
    private _http: HttpService,
    private _router: Router,
    private _activatedRoute: ActivatedRoute,
    private _storage: StorageService,
    private _httpRouter: HttpRouterService
  ) {}

  ngOnInit() {
    if (this._storage.getLocal('mobile')) {
      this.mobile = this._storage.getLocal('mobile');
    }
  }

  logIn($event) {
    $event.stopPropagation();
    if (!this.mobile) {
      alert('请输入手机号！');
      return;
    }
    if (!this.password) {
      alert('请输入密码！');
      return;
    }
    const param = 'mobile=' + this.mobile + '&password=' + this.password;
    this._http.post(this._httpRouter.logIn, param).then(res => {
      if (res.code === 1) {
        this.preference = 'cartype=' + res.data.cartype
                        + '&housetype=' + res.data.housetype
                        + '&accumulationfund=' + res.data.accumulationfund
                        + '&socialsecurity=' + res.data.socialsecurity;
        this._storage.setSession('userId', res.data.id);
        this._storage.setSession('token', res.data.token);
        this._storage.setSession('preference', this.preference);
        this._storage.setLocal('mobile', res.data.mobile);
        this._storage.setSessionObject('user', res.data);
        this._router.navigate(['/attache/home']);
      }else {
        alert(res.msg);
      }
    });
  }



}
